#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <sqlite3.h>
#import <UIKit/UIApplication.h>
#import <LockInfo/Plugin.h>

#import "framework/FWCommon.h"

#import "PICommon.h"
#import "PIContextSelectList.h"
#import "PIListAccess.h"
#import "PIIntegration.h"
#import "PIPlugin.h"
#import "PIStatus.h"


@implementation PIContextSelectList

@synthesize current, key, earliest;


static NSString* kTitleValue = @"MyTitle";


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithKey:(NSString*)newKey preferences:(FWPreferences*)prefs
{
    if ((self = [super init])) {
        self.key = newKey;
        
        if ([prefs boolValue:kPIOptionsHideFuture withDefault:kPIOptionsHideFutureDefault])
            self.earliest = [PIIntegration utcDateForLocalMidnight];
    }
    
    return self;
}

- (void)dealloc
{
    [earliest release];
    [current release];
    [key release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Handling user input

- (BOOL)cancelClicked:(FWApplication*)application sections:(NSArray*)sections
{
    return YES;
}

- (BOOL)selectClicked:(FWApplication*)application sections:(NSArray*)sections
{
    NSDictionary* section = [sections objectAtIndex:0];
    NSArray* items = [section objectForKey:FWDetailListViewSectionContents];
    NSMutableArray* contexts = [NSMutableArray arrayWithCapacity:[items count]];
    for (NSDictionary*item in items) {
        NSNumber* sw = (NSNumber*)[item objectForKey:FWDetailListViewFieldSwitch];
        
        if ([sw boolValue]) {
            NSString* title = (NSString*)[item objectForKey:kTitleValue];
            NSNumber* pk = (NSNumber*)[item objectForKey:PIContextFieldNameKey];
            
            [contexts addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                 pk, PIContextFieldNameKey,
                                 title, PIContextFieldNameTitle,
                                 nil]];
        }
    }
    
    [application setAttribute:self.key value:contexts];
    [application setAttribute:kPIApplicationContextCurrent value:contexts];
    
    ((PIStatus*)application.info).autoContextOn = NO;
    ((PIStatus*)application.info).fixedContextOn = YES;
    
    [((PIPlugin*)application.plugin) triggerUnconditionalRefresh];
    
    return YES;
}


// ******************************************************************************************
#pragma mark -
#pragma mark Accessing records from the database

- (NSArray*)dataForDetailListPage:(NSObject *)page application:(FWApplication *)application
{  
    self.current = (NSArray*)[application getAttribute:self.key];
    
    NSString *sql = [NSString stringWithFormat:
                     @"select c.id, c.name, c.icon, count(t.id)"
                     " from context c"
                     " left join task t on c.id = t.contextid and t.completeddate is null and t.tasktype <> 1 and (t.calendarID >=0 or t.calendarid = -2)"
                     "%@"
                     " group by c.id"
                     " order by c.name",
                     earliest ? [NSString stringWithFormat:@" and ifnull(t.startdate,0)<=%i", (int)[earliest timeIntervalSinceReferenceDate]] : @""];

    NSArray* record = FWDBGetRecords(sql, 1, application.databasePath, application, self);
    
    return [NSArray arrayWithObjects:[FWDetailListView sectionEntryForElements:record], nil];
}

- (NSObject*)objectForSQLRecord:(sqlite3_stmt*)sqlStatement withId:(NSInteger)sqlid application:(FWApplication*)application
{
    int cId = sqlite3_column_double(sqlStatement, 0);
    const char *cTitle = (const char*)sqlite3_column_text(sqlStatement, 1);
    const char *cIcon = (const char*)sqlite3_column_text(sqlStatement, 2);
    int cCount = sqlite3_column_double(sqlStatement, 3);
    
    NSString* title = [NSString stringWithUTF8String:(cTitle == NULL ? "" : cTitle)];
    NSString* icon = [NSString stringWithUTF8String:(cIcon == NULL ? "" : cIcon)];
    
    if ([icon length] > 0)
        title = [title stringByAppendingFormat:@" %@", icon];
    
    BOOL active = NO;
    for (NSDictionary* item in self.current) {
        NSNumber* pk = [item objectForKey:PIContextFieldNameKey];
        if ([pk intValue] == cId) {
            active = YES;
            break;
        }
    }

    NSDictionary* item = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                          title, FWDetailListViewFieldTitle,
                          [NSNumber numberWithBool:active], FWDetailListViewFieldSwitch,
                          [NSNumber numberWithInt:cId], PIContextFieldNameKey,
                          [NSString stringWithFormat:@" %d ", cCount], FWDetailListViewFieldTitleInfo,
                          title, kTitleValue,
                          nil];
    
    return item;
}

@end
